﻿using AlarmClock.BLL;
using AlarmClock.UI.Forms;
using Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace AlarmClock.UI
{
    public partial class FrmClockUpdate : Form
    {

        public ChangeClockHandler ChangeClock { get; set; }

        /// <summary>
        /// 闹钟服务
        /// </summary>
        private ClockBLL clockBLL = new ClockBLL();


        private Clock curClock;

        private string audioPath;
        private List<Audio> musics;

        public FrmClockUpdate(Clock clock, string order)
        {
            InitializeComponent();

            //窗体边框阴影效果
            PPWin32.SetClassLong(this.Handle, PPWin32.GCL_STYLE, PPWin32.GetClassLong(this.Handle, PPWin32.GCL_STYLE) | PPWin32.CS_DropSHADOW);

            this.btn_OK.Click += btn_Click;
            this.btn_UpdateMusicList.Click += btn_Click;
            this.btnClose.Click += (s, e) => { this.Close(); };

            this.time_Date.ValueChanged += new System.EventHandler(this.time_TextChanged);
            this.time_Hour.TextChanged += new System.EventHandler(this.time_TextChanged);
            this.time_Minute.TextChanged += new System.EventHandler(this.time_TextChanged);

            //添加音乐列表
            audioPath = Path.Combine(Application.StartupPath, ConfigurationManager.AppSettings["audio_Path"]);
            this.Clock_Music.Items.Clear();
            musics = GetFileNames(audioPath);
            this.Clock_Music.Items.AddRange(musics.Select(p => p.musicFileNameNoExten).ToArray());

            if (clock == null)//封装闹钟信息
            {
                //封装闹钟信息
                clock = new Clock()
                {
                    ClockName = this.Text,//闹钟名称
                    clockInfo = new ClockInfo()//闹钟的详细信息
                    {
                        time = DateTime.Now.AddMinutes(1).ToString("yyyy-MM-dd HH:mm:ss"),
                        repeat = Clock_Repeat.Text.Trim(),
                        music = Clock_Music.Text.Trim(),
                        things = Clock_Things.Text.Trim(),
                        nextInterval = Clock_Next_Interval.Text.Trim(),
                        musicVolume = music_Volume.Text.Trim(),
                        musicPlus = Clock_Music_Plus.Checked ? "1" : "0",
                        isActive = "1"
                    }
                };
            }
            else
            {
                string repeat = clock.clockInfo.repeat.Trim();
                if (!Clock_Repeat.Items.Contains(repeat)) Clock_Repeat.Items.Add(repeat);
                Clock_Repeat.SelectedIndex = Clock_Repeat.Items.IndexOf(repeat); //重复

                Clock_Music.SelectedIndex = Clock_Music.Items.IndexOf(Path.GetFileNameWithoutExtension(clock.clockInfo.music.Trim())); //音乐
                Clock_Things.Text = clock.clockInfo.things.Trim(); //备注
                Clock_Next_Interval.Text = clock.clockInfo.nextInterval.Trim(); //稍后提醒
                music_Volume.Text = clock.clockInfo.musicVolume.Trim(); //音量
                Clock_Music_Plus.Checked = clock.clockInfo.musicPlus == "1"; //响铃时震动
            }
            this.curClock = clock;
            this.Text = order.ToString();
            //时间，无论增加还是修改都会更新
            this.time_Hour.Text = clock.clockInfo.time.Substring(11, 2); //时钟
            this.time_Minute.Text = clock.clockInfo.time.Substring(14, 2); //分钟
            this.time_Date.Value = DateTime.Parse(clock.clockInfo.time);//日期

        }

        private void btn_Click(object sender, EventArgs e)
        {
            var btn = (Button)sender;
            switch (btn.Name)
            {
                case "btn_OK":
                    OnChangeClock(curClock, this.Text);
                    break;

                case "btn_UpdateMusicList":
                    FrmUpdateMusicList frmUpdateMusicList = new FrmUpdateMusicList(musics, audioPath);
                    _ = frmUpdateMusicList.ShowDialog();
                    this.Clock_Music.Items.Clear();
                    this.Clock_Music.Items.AddRange(musics.Select(p => p.musicFileNameNoExten).ToArray());
                    break;

                default:
                    break;
            }
        }

        /// <summary>
        /// 修改闹钟的函数，执行完会触发回调，更新UI
        /// </summary>
        /// <param name="clock"></param>
        /// <param name="order"></param>
        private void OnChangeClock(Clock clock,string order)
        {
            string clockName=clock.ClockName;
            string hour = time_Hour.Text.Trim(), minute = time_Minute.Text.Trim();
            hour = hour.PadLeft(2, '0');
            minute = minute.PadLeft(2, '0');

            string repeat = Clock_Repeat.Text.Trim();
            string music = Clock_Music.Text.Trim();
            string things = Clock_Things.Text.Trim();
            string next = Clock_Next_Interval.Text.Trim();
            string musicVolume = Clock_Music_Volume.Text.Trim();
            string musicPlus = Clock_Music_Plus.Checked ? "1" : "0";
            string isActive = "1";

            if (!IsValidInput(hour, minute, repeat, music, next, musicVolume))
            {
                return;
            }

            //存储音乐的后缀名
            music = musics?.First(p => p.musicFileNameNoExten == Clock_Music.Text).musicFileName;

            //封装闹钟信息
            curClock = new Clock()
            {
                ClockName = clockName,//闹钟名称
                clockInfo = new ClockInfo()//闹钟的详细信息
                {
                    time = $"{time_Date.Value.ToString("yyyy-MM-dd")} {hour}:{minute}:00",
                    repeat = repeat,
                    music = music,
                    things = things,
                    nextInterval = next,
                    musicVolume = musicVolume,
                    musicPlus = musicPlus,
                    isActive = isActive
                }
            };
            ChangeClock?.Invoke(curClock, order);//执行委托实例，让主界面去做事情
            this.Close();
        }

        /// <summary>
        /// 验证输入是否有效
        /// </summary>
        /// <param name="hour">时钟</param>
        /// <param name="minute">分钟</param>
        /// <param name="repeat">重复</param>
        /// <param name="music">铃声</param>
        /// <param name="next">稍后提醒</param>
        /// <param name="volume">闹钟音量</param>
        /// <returns></returns>
        private bool IsValidInput(string hour,string minute,string repeat,string music,string next,string volume)
        {
            bool res = true;
            string msg = "";
            if (string.IsNullOrEmpty(hour) || int.Parse(hour) < 0 || int.Parse(hour) > 23)
            { res = false; msg = "【时钟】输入数值应在【0-23】区间"; time_Hour.Focus(); }
            else if (string.IsNullOrEmpty(minute) || int.Parse(minute) < 0 || int.Parse(minute) > 59)
            { res = false; msg = "【分钟】输入数值应在【0-60】区间"; time_Minute.Focus(); }
            //else if (!Clock_Repeat.Items.Contains(repeat))
            //{ res = false; msg = "【重复】请选择正确选项"; Clock_Repeat.Focus(); }           
            else if ((!repeat.StartsWith("每") && (!repeat.EndsWith("天") || !repeat.EndsWith("周") || !repeat.EndsWith("月"))))
            {
                if(!Clock_Repeat.Items.Contains(repeat))//改为每【数字】天/周/月可以
                {
                    res = false; 
                    msg = "【重复】请选择正确选项";
                    Clock_Repeat.Focus();
                }
            }                
            else if (!Clock_Music.Items.Contains(music))
            { res = false; msg = "【铃声】请选择正确选项"; Clock_Music.Focus(); }
            else if (!Clock_Next_Interval.Items.Contains(next))
            { res = false; msg = "【稍后提醒】请选择正确选项"; Clock_Next_Interval.Focus(); }
            else if (!Clock_Music_Volume.Items.Contains(volume))
            { res = false; msg = "【闹钟音量】请选择正确选项"; Clock_Music_Volume.Focus(); }

            if (!res)
            {
                MessageBox.Show(msg); //验证不通过在这里弹窗
            }
            return res;
        }

        /// <summary>
        /// 获取音乐文件列表
        /// </summary>
        /// <param name="dirPath"></param>
        /// <returns></returns>
        private List<Audio> GetFileNames(string dirPath)
        {
            var files=Directory.GetFiles(dirPath);
            var audios =new List<Audio>();
            foreach (var file in files)
            {
                audios.Add(new Audio() { musicfullPath = file });
            }
            return audios;
        }

        private void time_TextChanged(object sender, EventArgs e)
        {
            string date = time_Date.Value.ToString("yyyy-MM-dd");
            string hour = time_Hour.Text.Trim(), minute = time_Minute.Text.Trim();

            if (hour == "" || int.Parse(hour) < 0 || int.Parse(hour) >= 24)
            {
                hour = "00";
            }

            if (minute == "" || int.Parse(minute) < 0 || int.Parse(minute) >= 60)
            {
                minute = "00";
            }

            var diff = clockBLL.GetMinDisTime($"{date} {hour}:{minute}:00");//距离【闹钟】响的时差
            string msg = "";
            if (diff == null)
            {
                msg = "当前没有闹钟";
            }
            else
            {
                msg = $"{diff.Day} 天 {diff.Hour} 小时 {diff.Minute} 分钟后闹钟响";
                if (diff.Day >= 0 && diff.Hour >= 0)
                {
                    if (diff.Minute == 0)
                    {
                        msg = "不到 1 分钟后闹钟响";
                    }
                }
            }
            Clock_Tips.Text = msg;
        }

    }
}
